package linear.queue.base;

import linear.linked.base.MyLinked;

/**
 * 链表实现队列
 *
 * @author yeyangtao created at 10:15 2020/9/23
 */
public class MyLinkedQueue<T> implements MyQueue<T> {
    MyLinked<T> first;
    MyLinked<T> last;
    int size = 0;

    @Override
    public boolean offer(T o) {
        MyLinked<T> l = last;
        MyLinked<T> newNode = new MyLinked<>(o);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.setNext(newNode);
        size++;
        return true;
    }

    @Override
    public T poll() {
        if (first == null) return null;
        T result = first.getValue();
        //删除队头
        first = first.getNext();
        size--;
        return result;
    }

    @Override
    public T peek() {
        if (first == null) return null;
        return first.getValue();
    }

    @Override
    public boolean isEmpty() {
        return first == null;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public String toString() {
        if (first == null) return "[]";
        StringBuilder sb = new StringBuilder("[");
        MyLinked<T> linked = first;
        while (linked != null) {
            sb.append(linked.getValue().toString());
            linked = linked.getNext();
            if (linked != null) sb.append(", ");
        }
        return sb.append("]").toString();
    }
}
